<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" @keyup.native.enter="getUserList" :clearable="true"
                    @clear="clearCallBack">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="stateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="scopeInfo">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="editUserFrom(scopeInfo.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="deleteUser(scopeInfo.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scopeInfo.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[1, 3, 5, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
    </el-card>

    <!--  添加用户 dialog  -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" @closed="dialogClosed('addFormRef')">
      <el-form :model="addUsersForm" :rules="addUsersRules" ref="addFormRef">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="addUsersForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth">
          <el-input v-model="addUsersForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="addUsersForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="addUsersForm.mobile" minlength="11" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </div>
    </el-dialog>

    <!--  编辑用户 dialog  -->
    <el-dialog title="编辑用户" :visible.sync="editDialogVisible" @closed="dialogClosed('editFormRef')">
      <el-form :model="editUsersForm" :rules="editUsersRules" ref="editFormRef">
        <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
          <el-input v-model="editUsersForm.username" disabled="disabled"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
          <el-input v-model="editUsersForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile" :label-width="formLabelWidth">
          <el-input v-model="editUsersForm.mobile" minlength="11" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUserInfo">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @closed="setRoleDialogClosed">
      <el-form label-width="130px" :model="nowUser">
        <el-form-item label="当前的用户">
          <el-input v-model="nowUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前的角色">
          <el-input v-model="nowUser.role_name" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配新角色">
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  apiGetUsers,
  apiUpdateUsersState,
  apiAddUser,
  apiQueryUserInfo,
  apiUpdateUserInfo,
  apiDeleteUser,
  apiGetRoles,
  apiAllotRole
} from '@/api/index.js'

export default {
  data () {
    // 正则验证邮箱
    let checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 正则验证手机9
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 10
      },
      userlist: [],
      total: 0,
      // 添加用户
      addDialogVisible: false,
      addUsersForm: {},
      formLabelWidth: '80px',
      addUsersRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户
      editDialogVisible: false,
      editUsersForm: {},
      editUsersRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配权限
      setRoleDialogVisible: false,
      nowUser: {},
      selectedRoleId: '',
      rolesList: []
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList () {
      const { data: res } = await apiGetUsers(this.queryInfo)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败！')
      }
      this.userlist = res.data.users
      this.total = res.data.total
    },
    // 监听 pagesize 改变的事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 清空搜索框回调
    clearCallBack () {
      this.getUserList()
    },
    // 修改用户状态
    async stateChange (userInfo) {
      let { data: res } = await apiUpdateUsersState(userInfo)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status + ' ' + res.meta.msg)
      }
      this.$message.success('用户状态更新成功')
    },
    // 对话框关闭回调 清空表单
    dialogClosed (ref) {
      this.$refs[ref].resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await apiAddUser(this.addUsersForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.status + ' ' + res.meta.msg)
        }
        this.addDialogVisible = false
        this.$message.success('添加用户成功!')
        this.getUserList()
      })
    },
    // 打开编辑用户对话框，查询用户详细信息
    async editUserFrom (id) {
      this.editDialogVisible = true
      let { data: res } = await apiQueryUserInfo(id)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.status + ' ' + res.meta.msg)
      }
      this.editUsersForm = res.data
    },
    // 更新用户信息
    async updateUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        let { data: res } = await apiUpdateUserInfo(this.editUsersForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.status + ' ' + res.meta.msg)
        }
        this.editDialogVisible = false
        this.$message.success('更新用户信息成功')
        this.getUserList()
      })
    },
    // 删除用户
    async deleteUser (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let { data: res } = await apiDeleteUser(id)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.status + ' ' + res.meta.msg)
        }
        this.$message.success('删除用户成功')
        this.getUserList()
      }).catch(() => {
      })
    },
    // 点击分配角色按钮
    async setRole (info) {
      this.setRoleDialogVisible = true
      this.nowUser = info
      const { data: res } = await apiGetRoles()
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.rolesList = res.data
    },
    // 分配角色 对话框关闭回调
    setRoleDialogClosed () {
      this.selectedRoleId = ''
    },
    // 分配角色
    async saveRoleInfo () {
      const { data: res } = await apiAllotRole(this.nowUser.id, this.selectedRoleId)
      this.setRoleDialogVisible = false
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.$message.success('分配角色成功')
      this.getUserList()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
